﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections;
using System.Dynamic;
using System.Threading.Tasks;

namespace Developer.Core.FrameWork.Common.Results
{
    /// <summary>
    /// 中台通用结果包装器
    /// </summary>
    public class MiddlePlatformResultWapper : IAsyncResultFilter
    {
        public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            if(context.Result is ObjectResult objectResult)
            {
                int? StatusCode = objectResult.StatusCode;
                if (StatusCode == 200 || StatusCode == 201 || StatusCode == 202 ||
                    !StatusCode.HasValue)
                    // 1、包装正常结果
                    objectResult.Value = WapperSuccessResult(objectResult);
                else
                    // 2、包装异常结果
                    objectResult.Value = WapperFailResult(objectResult);
            }

            await next();
        }

        public object WapperSuccessResult(object obj)
        {
            // 1、创建返回结果
            dynamic warpResult = new ExpandoObject();
            warpResult.Success = "true";
            warpResult.ErrorInfo = "";

            // 2、判断是否为字典
            if (obj.GetType().Name.Contains("Dictionary"))
            {
                // 2.1、判断是否包含ErrorInfo
                IDictionary dic = (IDictionary)obj;
                if (dic.Contains("ErrorInfo"))
                {
                    warpResult.Success = dic["Success"];
                    warpResult.ErrorInfo = dic["ErrorInfo"];

                    // 2.2、删除字典子里面的Success，ErrorInfo
                    dic.Remove("Success");
                    dic.Remove("ErrorInfo");
                }
            }

            warpResult.Result = new JsonResult(obj).Value;

            return warpResult;
        }

        public object WapperFailResult(ObjectResult obj)
        {
            dynamic warpResult = new ExpandoObject();
            warpResult.Success = obj.StatusCode;

            if(obj.Value is string info)
            {
                // 1、字符串异常信息
                warpResult.ErrorInfo = info;
            }
            else
            {
                // 2、类型异常信息
                warpResult.ErrorInfo = new JsonResult(obj.Value).Value;
            }

            return warpResult;
        }
    }
}
